import axios, { type Method } from 'axios'
import { useUserStore } from '../stores'
import { showToast } from 'vant'
import router from '@/router'

const baseURL = 'https://consult-api.itheima.net/'
//配置
const instance = axios.create({
  baseURL,
  timeout: 5000
})

//请求拦截器
instance.interceptors.request.use(
  (config) => {
    //做很多事情
    const store = useUserStore()
    if (store.user?.token && config.headers) {
      config.headers.Authorization = 'Bearer ' + store.user?.token
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

//响应拦截器  1.剥离无效数据,res.data.data,2.处理状态码
instance.interceptors.response.use(
  (res) => {
    //做很多事情
    if (res.data.code != 10000) {
      showToast(res.data.message || '业务失败')
    }

    return res.data
  },
  (err) => {
    //token,401
    if (err.response?.status === 401) {
      // 删除用户信息
      const store = useUserStore()
      store.delUser()
      // 跳转登录，带上接口失效所在页面的地址，登录完成后回跳使用
      router.push({
        path: '/login',
        query: { returnUrl: router.currentRoute.value.fullPath }
      })
    }
    return Promise.reject(err)
  }
)

//fullPath

//  /user   /user?key=100

type Data<T> = {
  code: number
  message: string
  data: T
}

const request = <T>(
  url: string,
  method: Method = 'get',
  submitData?: object
) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}

export { request, baseURL }
